package com.kpmg.datalake.common.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kpmg.datalake.common.dao.CompanyInfoMapper;
import com.kpmg.datalake.common.dao.DateInfoMapper;
import com.kpmg.datalake.common.dynamicdatasource.DynamicDS;
import com.kpmg.datalake.common.model.DimInfo;
import com.kpmg.datalake.common.model.DateInfo;
import com.kpmg.datalake.common.model.ReportDate;
import com.kpmg.datalake.common.service.BaseInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BaseInfoServiceImpl implements BaseInfoService {

    @Autowired
    private CompanyInfoMapper demoMapper;
    @Autowired
    private DateInfoMapper dateInfoMapper;

    @Override
    @DynamicDS("projectId")
    public PageInfo<DimInfo> initCorp(int page, int size, String projectId, String param) {

    	if(size != -1)
    	{
    		PageHelper.startPage(page, size);
    	}

        List<DimInfo> result = demoMapper.initCorp(param);

        return new PageInfo<DimInfo>(result);
    }
    
    @Override
    @DynamicDS("projectId")
    public PageInfo<DimInfo> getLastLevelCorp(int page, int size, String projectId, String param) {
    	if(size != -1) {
    		PageHelper.startPage(page, size);
    	}
    	List<DimInfo> result = demoMapper.getLastLevelCorp(param);

        return new PageInfo<>(result);
    }
    
    /**
     * 初始化报表会计期间
     */
	@Override
	@DynamicDS("projectId")
	public List<ReportDate> initDate(String projectId) {
		List<ReportDate> reportDates = new ArrayList<>();
		// 查询报表会计期间
		List<DateInfo> dateInfoList = dateInfoMapper.initDate();
		Map<String, List<DateInfo>> map = new HashMap<>();
		// 依据年份分组
		dateInfoList.forEach(dateInfo -> {
			String year = dateInfo.getAcgYr();
			if (map.containsKey(year)) {
				map.get(year).add(dateInfo);
			} else {
				List<DateInfo> dateList = new ArrayList<>();
				dateList.add(dateInfo);
				map.put(year, dateList);
			}
		});
		// 月份排序
		map.forEach((key, value) -> {
			ReportDate reportDate = new ReportDate();
			reportDate.setYear(key);
			Collections.sort(value, (m1, m2) -> {
				return m1.getSaleDtBgn().compareTo(m2.getSaleDtBgn());
			});
			reportDate.setReportDates(value);
			reportDates.add(reportDate);
		});
		return reportDates;
	}

}
